package web

import (
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"rlhs/fr"
)

func ImageRecognitionHandler(rw http.ResponseWriter, req *http.Request) {
	ir := fr.NewImageRecognition()
	var input = map[string]string{
		"id_card":      req.FormValue("id_card"),
		"name":         req.FormValue("name"),
		"image_base64": req.FormValue("image_base64"),
		"optional":     req.FormValue("optional"),
	}

	file, _, err := req.FormFile("image_file")
	if err == nil {
		bytes, err := ioutil.ReadAll(file)
		if err != nil {
			log.Print(rw, err.Error())
			return
		}
		imageBase64 := base64.StdEncoding.EncodeToString(bytes)
		input["image_base64"] = imageBase64
	}

	res, err := ir.Recognition(input)
	if err != nil {
		log.Print(rw, err.Error())
		return
	}
	fmt.Printf("%s", res)
	fmt.Fprintf(rw, res)
}
